package com.partners.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.partners.configure.wechatmp.WxMpProperties;
import com.partners.constant.ErrorMessageEnum;
import com.partners.constant.PermissionEnum;
import com.partners.dao.dto.UserInfoOutputDTO;
import com.partners.dao.dto.UserInputDTO;
import com.partners.dao.basic.*;
import com.partners.dao.bo.*;
import com.partners.model.BusinessException;
import com.partners.model.Paging;
import com.partners.service.UploadFileService;
import com.partners.service.UserService;
import com.partners.utils.CodeUtils;
import com.partners.utils.TimestampUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liangyongle
 * @date 2018-12-04
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Resource
    private CustomerDao customerDao;

    @Resource
    private WxMpProperties wxMpProperties;

    @Resource
    private UserRoleDao userRoleDao;

    @Resource
    private UserGroupDao userGroupDao;

    @Resource
    private UploadFileService uploadFileService;

    @Resource
    private FansDao fansDao;



    /**
     * 获取合伙人的个人信息
     * @param id Integer
     * @return Object
     * */
    @Override
    public UserInfoOutputDTO getUserInfo(Integer id) {
        //Map<String,Object> user = userDao.getUserInfoById(id);
        UserInfoOutputDTO user = userDao.getUserInfoById(id);
        if(user != null){
            //获取分组
           GroupDO group = userGroupDao.selectByUserId(id);
           if(group != null){
               user.setGroupName(group.getName());
           }
        }
        return user;
    }


    /**
     * 根据获取用户的信息
     * @param id Integer
     * @return Object
     * */
    @Override
    public UserDO getUserById(Integer id) {
        UserDO userDO = userDao.selectByPrimaryKey(id);
        return userDO;
    }


    /**
     * 获取合伙人详情
     * @Param id Integer
     * return Object
     * */
    @Override
    public UserInfoOutputDTO getuserDetailById(Integer id) {
        UserInfoOutputDTO detail = userDao.getUserDetailById(id);
        if(detail == null){
            throw  BusinessException.of(ErrorMessageEnum.USER_NOT_EXIST);
        }
        //查询分组
        String groupName =userDao.getGroupNameByUid(id);
        detail.setGroupName(groupName);
        return detail;
    }

    /**
     * 获取报备管理所有的用户列表
     * @Param id Integer
     * return Object
     * */
    @Override
    public Map<String, Object> getAllCustomerList(Paging paging, String name, BigInteger phone) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        Integer nowtime = TimestampUtils.timestamp();
        List<Map<String,Object>> list =  customerDao.selectAllCustomerList();
        String status = "待领券";
        Integer nowTime= TimestampUtils.timestamp();
        Integer overTime = 0;
        for (Map<String,Object> map:list){
            if((Integer) map.get("verification") == 1){
                //已经核销
                status = "已成交";
            }else if(map.get("openid").equals("")){
                status = "待领券";
            }else if((nowTime - (Integer) map.get("addtime"))/3600/24 > 7){
                status = "已过期";
            }else{
                overTime = 7-(nowTime - (Integer) map.get("addtime"))/3600/24;
                status = "已领券";
            }
            map.put("status",status);
            map.put("overTime",overTime);
            String timeFormat = "yyyy-MM";
            String addtime = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("addtime"),timeFormat);
            map.put("addtime",addtime);
        }
        PageInfo page = new PageInfo(list);
        Object total = page.getTotal();
        allList.put("total",total);
        allList.put("list",list);
        return allList;
    }


    /**
     * 删除用户
     * @param id Integer
     * @return boolean
     * */
    @Override
    @Transactional
    public void deleteUser(Integer id) {
        //删除用户
        userDao.deleteByPrimaryKey(id);
        //删除角色绑定
        userRoleDao.deleteByPrimaryKey(id);
        //删除用户组绑定
        userGroupDao.deleteByUid(id);
    }



    /**
     * 新增用户
     * @param userInputDTO UserInputDTO
     * @return boolean
     * */
    @Override
    @Transactional
    public Integer editUser(UserInputDTO userInputDTO) {

        if(userInputDTO.getPid() == null){
            throw BusinessException.of(ErrorMessageEnum.PID_NOT_FOND);
        }
        Integer exist = userDao.getUserInfoByPhone(userInputDTO.getPhone(),userInputDTO.getId());
        String baseUrl = wxMpProperties.getBaseUrl();
        String url =baseUrl+"/loginPage/index?bind=";
        if(exist != null){
            throw BusinessException.of(ErrorMessageEnum.PHONE_IS_EXIST);
        }
        Integer result = 0;
        UserDO userDO = new UserDO();
        userDO.setName(userInputDTO.getName());
        userDO.setPhone(userInputDTO.getPhone());
        userDO.setPid(userInputDTO.getPid());
        if(userInputDTO.getId()  != null){
            //编辑
            userDO.setId(userInputDTO.getId());
            //生成二维码
            String codeUrl =  url + userDO.getId();
            String qrcode = uploadFileService.createQrcode(codeUrl);
            userDO.setQrcode(qrcode);
            userDao.updateByPrimaryKeySelective(userDO);
            result = userInputDTO.getId();
            //查询当前的用户是否有
        }else{
            //新增
            //先获取最后一条的code的值
            Integer lastCode = userDao.getLastCode();
            String code = CodeUtils.getNewUserCode(lastCode);
            userDO.setCode( Integer.parseInt(code));
            userDO.setAddtime(TimestampUtils.timestamp());
            userDao.insertSelective(userDO);
            result = userDO.getId();
            UserDO user = new UserDO();
            Integer newId = userDO.getId();
            //生成二维码
            String qrcode = uploadFileService.createQrcode(url + newId);
            user.setQrcode(qrcode);
            user.setId(newId);
            userDao.updateByPrimaryKeySelective(user);
            //插入角色
            UserRoleDO userRoleDO = new UserRoleDO();
            userRoleDO.setUid(newId);
            userRoleDO.setRoleId(userInputDTO.getRoleId());
            userRoleDO.setAddtime(TimestampUtils.timestamp());
            userRoleDao.insert(userRoleDO);

            if(userInputDTO.getGroupId() != null){
                //插入分组
                UserGroupDO userGroupDO = new UserGroupDO();
                userGroupDO.setUserId(newId);
                userGroupDO.setGroupId(userInputDTO.getGroupId());
                userGroupDO.setAddtime(TimestampUtils.timestamp());
                userGroupDao.insert(userGroupDO);
            }
        }
        return result;
    }



    /**
     * 获取旗下用户列表
     * @Param paging Paging uid Integer
     * return List
     * */
    @Override
    public Map<String, Object> getUserListByUid(Paging paging, Integer uid,Integer returnType) {
         PageHelper.startPage(paging.getPage(),paging.getRows());
         Map<String,Object> allList = new HashMap<>();
         List<Map<String,Object>>  list =  userDao.getUserByUid(uid);
        for (Map<String,Object> map : list){
            String timeFormat = "yyyy-MM-dd HH:mm:ss";
            String addtime = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("addtime"),timeFormat);
            String dateFormat = "yyyy-MM";
            String format = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("addtime"),dateFormat);
            map.put("addtime",addtime);
            map.put("format",format);
            map.put("point",(Integer) map.get("point") !=null?(Integer) map.get("point"):0);
        }
        PageInfo pageInfo = new PageInfo(list);
        Object total = pageInfo.getTotal();
        allList.put("total",total);
        if(returnType == 1){
            Map<Object, List<Map<String, Object>>> timeList = list.stream().collect(Collectors.groupingBy(i -> i.get("format")));
            TreeMap<Object, List<Map<String, Object>>> treeMap = new TreeMap<>();
            treeMap.putAll(timeList);
            NavigableMap<Object, List<Map<String, Object>>> descendingMap = treeMap.descendingMap();
            allList.put("list",descendingMap);
        }else{
            allList.put("list",list);
        }
        return allList;
    }



    /**
     *判断该用户是否拥有该权限
     *param uid Integer code Integer
     *return boolean
     * */
    public  boolean hasPermission(Integer uid, Integer code){
        List<PermissionDO>  permission = userDao.getRolePermissionByUid(uid);
        if(permission !=null){
            List<Integer> collect = permission.stream().map(PermissionDO::getCode).collect(Collectors.toList());
            if(collect.contains(code)){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }


    /**
     *判断该用户是否拥有该权限
     * param uid Integer code Integer
     * return boolean
     * */
    public  void isPermission(Integer uid, Integer code){
        List<PermissionDO>  permission = userDao.getRolePermissionByUid(uid);
        if(permission == null){
            throw BusinessException.of(ErrorMessageEnum.HANDLE_NOT_FOUNT);
        }
        List<Integer> collect = permission.stream().map(PermissionDO::getCode).collect(Collectors.toList());
        if(!collect.contains(code)){
            throw BusinessException.of(ErrorMessageEnum.HANDLE_NOT_FOUNT);
        }

    }



    /**
     * 获取我的推荐人
     * @param uid Integer
     * @return String
     * */
    @Override
    public UserDO getMyRecommondUser(Integer uid) {
        UserDO user = userDao.getMyRecommondUserById(uid);
        return user;
    }


    /**
     * 控制用户积分是否显示
     * @Param uid Integer show Integer
     * return boolean
     * */
    @Override
    public void changePointShow(Integer uid, Integer show) {
        UserDO user = userDao.selectByPrimaryKey(uid);
        if(user == null){
            throw BusinessException.of(ErrorMessageEnum.USER_NOT_EXIST);
        }
        UserDO userDO = new UserDO();
        userDO.setId(uid);
        userDO.setPointShow(show.byteValue());
        userDao.updateByPrimaryKeySelective(userDO);

    }



    /**
     * 获取所有的用户列表
     *@Param paging Paging
     *@return list
     * */
    @Override
    public Map<String, Object> getAllUserList(Paging paging, Integer returnType) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        List<Map<String, Object>> list = userDao.allUserList();
        for (Map<String,Object> map : list){
            String timeFormat = "yyyy-MM-dd HH:mm:ss";
            String addtime = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("addtime"),timeFormat);
            String dateFormat = "yyyy-MM";
            String format = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("addtime"),dateFormat);
            map.put("addtime",addtime);
            map.put("format",format);
            map.put("point",(Integer) map.get("point") !=null?(Integer) map.get("point"):0);
        }
        PageInfo pageInfo = new PageInfo(list);
        Object total = pageInfo.getTotal();
        allList.put("total",total);
        if(returnType == 1){
            Map<Object, List<Map<String, Object>>> timeList = list.stream().collect(Collectors.groupingBy(i -> i.get("format")));
            TreeMap<Object, List<Map<String, Object>>> treeMap = new TreeMap<>();
            treeMap.putAll(timeList);
            NavigableMap<Object, List<Map<String, Object>>> descendingMap = treeMap.descendingMap();
            allList.put("list",descendingMap);
        }else{
            allList.put("list",list);
        }
        return allList;
    }


}
